package com.aco.fatureapp.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;

import com.aco.fatureapp.R;
import com.aco.fatureapp.model.billing.LogLeitura;

public class NoteFragment extends DialogFragment {

	LogLeitura mLogLeitura;

	EditText txtNote;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.DialogFragment#onCreateDialog(android.os.Bundle)
	 */
	@Override
	@SuppressLint("InflateParams")
	public Dialog onCreateDialog(final Bundle savedInstanceState) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(
				getActivity(), R.style.MyDialog);

		final View view = getActivity().getLayoutInflater().inflate(
				R.layout.fragment_note, null);

		mLogLeitura = (LogLeitura) getArguments().getSerializable(
				LogLeitura.getTableName(LogLeitura.class));

		builder.setView(view).setTitle("Observação");

		builder.setPositiveButton("Salvar",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(final DialogInterface dialog,
							final int which) {
						mListener.onDialogPositiveClick(NoteFragment.this);
					}
				});

		builder.setNeutralButton("Cancelar", null);

		txtNote = (EditText) view.findViewById(R.id.txtNote);

		exibirObservacao();

		return builder.create();
	}

	/**
	 * Responsável por exibir uma observação previamente cadastrada
	 */
	private void exibirObservacao() {
		txtNote.setFilters(new InputFilter[] { new InputFilter.AllCaps() });

		if (mLogLeitura != null && mLogLeitura.getObservacao() != null) {
			txtNote.setText(mLogLeitura.getObservacao());
		}
	}

	/* ########### GETTERS / SETTERS ############# */

	public EditText getTxtNote() {
		return txtNote;
	}

	public void setTxtNote(final EditText txtNote) {
		this.txtNote = txtNote;
	}

	/* ########### LISTENER INTERFACE ############# */

	public interface NoteListener {
		public void onDialogPositiveClick(DialogFragment dialog);
	}

	// Usa essa instância da interface para entregar eventos de ação
	NoteListener mListener;

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.DialogFragment#onAttach(android.app.Activity)
	 */
	@Override
	public void onAttach(final Activity activity) {
		super.onAttach(activity);
		try {
			mListener = (NoteListener) activity;
		}
		catch (final ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " deve implementar NoteListener");
		}
	}
}